import { JSONObject } from 'admin/schema/common';
import { Menu } from 'antd';
import { filter, find, isEmpty, reduce, startsWith } from 'lodash';
import { siderBarConfig } from 'permission/menuConfig';
import * as React from 'react';
import { useEffect, useMemo, useState } from 'react';
import { useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { getSiderBarMenu } from 'utils';
import { smsAuth } from 'admin/servers/servers';
import { flatTryCatch } from '../servers/http';

export const casMenuPermission = {
  '/webapp/casSystem/organizations': 'SYSTEM_SETTING_ORG_MANAGE',
  '/webapp/casSystem/roles': 'SYSTEM_SETTING_ROLE_MANAGE',
  '/webapp/casSystem/users': 'SYSTEM_SETTING_USER_MANAGE',
  '/webapp/casSystem/sensitiveWord': 'SYSTEM_SETTING_SENSITIVE_WORD_MANAGE',
  '/webapp/casSystem/apiToken': 'SYSTEM_SETTING_API_TOKEN_MANAGE',
  '/webapp/casSystem/operationLog': 'SYSTEM_SETTING_OPERATION_LOG',
  '/webapp/casStatistics/industrySms': 'DATA_STATISTICS_INDUSTRY_SMS',
  '/webapp/casStatistics/targetedSms': 'DATA_STATISTICS_TARGETED_SMS',
  '/webapp/casStatistics/intelligentCall': 'DATA_STATISTICS_INTELLIGENT_CALL',
  '/webapp/casStatistics/billing': 'DATA_STATISTICS_BILLING',
};

// 页面目录 能展开的
const pageCatalog = [
  '/webapp/industrySms',
  '/webapp/targetSms',
  '/webapp/outbound',
  '/webapp/outbound/task',
  '/webapp/outbound/ai',
  '/webapp/outbound/client',
  '/webapp/outbound/system',
  '/webapp/casSystem',
  '/webapp/casStatistics',
];

export const SideMenu: React.FC = () => {
  const history = useHistory();

  const [lock, setLock] = useState<boolean>(true); // 行短、靶向、外呼权限统一请求锁，锁住代表还在请求

  /** 获取当前用户权限 data行短，target靶向，外呼call */
  // 0未开通 1审核中 2审核通过 3驳回
  const [userSmsAuth, setUserSmsAuth] = useState({ data: 0, target: 0, call: 0 });
  const getIndustryAuth = async () => {
    setLock(true);
    const {
      response: { data, target, call },
      error,
    } = await flatTryCatch(smsAuth());
    setLock(false);
    if (error) return;
    const auth = { data, target, call };
    setUserSmsAuth(auth);
    sessionStorage.setItem('smsAuth', JSON.stringify(auth));
    // sessionStorage.setItem('smsAuth', JSON.stringify({ data: 2, target: 12, call: 2 }));
  };
  useEffect(() => {
    getIndustryAuth();
  }, []);

  /**菜单显示*/
  const [openKeys, setOpenKeys] = useState(undefined as any);
  const loginInfo = useSelector((state: JSONObject) => state.loginInfo);
  const pathname = location.pathname; // 当前路由

  /**展开的目录*/
  const currentOpenKeys = useMemo((): string[] => {
    const subPath = [];
    for (const item of pageCatalog) {
      if (pathname.includes(item)) {
        subPath.push(item);
      }
    }
    // 在路由变化时重置，设置当前展开的
    setOpenKeys(subPath);
    return subPath;
  }, [pathname]);

  // SubMenu 展开/关闭
  const onOpenChange = (keys: Array<string>) => {
    // 请求期间，不能打开
    if (lock) return;

    // 行短
    if (userSmsAuth.data !== 2 && keys.includes('/webapp/industrySms')) {
      history.push(`/401/noSmsAuth?state=${userSmsAuth.data}`);
      return;
    }

    // 靶向
    if (userSmsAuth.target !== 2 && keys.includes('/webapp/targetSms')) {
      history.push(`/401/noSmsAuth?state=${userSmsAuth.target}`);
      return;
    }

    // 外呼
    if (userSmsAuth.call !== 2 && keys.includes('/webapp/outbound')) {
      history.push(`/401/noSmsAuth?state=${userSmsAuth.call}`);
      return;
    }

    setOpenKeys(keys);
  };

  /** 菜单渲染 */
  const newSiderBarConfig = reduce(
    siderBarConfig,
    (prev, item) => {
      if (
        startsWith(item.path, '/webapp/casSystem') ||
        startsWith(item.path, '/webapp/casStatistics')
      ) {
        const submenu = filter(item.children, item =>
          find(loginInfo?.permissions, { code: casMenuPermission[item.path] })
        );
        if (!isEmpty(submenu)) {
          return [...prev, { ...item, children: submenu }];
        }
        return prev;
      }
      // 外呼 只有限制的这3个角色才能看到 系统配置
      if (startsWith(item.path, '/webapp/outbound')) {
        const targetCodesSet = new Set([
          'CHAO_JI_GUAN_LI_YUAN',
          'SHU_JU_JU_GUAN_LI_YUAN',
          'JI_TUAN_GUAN_LI_YUAN',
        ]);
        const hasPermission = loginInfo?.roles.some(role => targetCodesSet.has(role.code));
        if (!hasPermission) {
          const permissionChildren = item.children.filter(
            ({ path }) => path !== '/webapp/outbound/system'
          );
          return [...prev, { ...item, children: permissionChildren }];
        }
      }
      return [...prev, item];
    },
    []
  );

  return (
    <div className="menu-wrap ">
      <Menu
        mode="inline"
        openKeys={openKeys}
        onOpenChange={onOpenChange}
        defaultOpenKeys={currentOpenKeys}
        selectedKeys={[pathname]} // 高亮
      >
        {getSiderBarMenu(newSiderBarConfig)}
      </Menu>
    </div>
  );
};
